package com.lagou.service.impl;

import com.lagou.pojo.Article;
import com.lagou.repository.ArticleRepository;
import com.lagou.service.ArticleService;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ArticleServiceImpl implements ArticleService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleRepository articleRepository;


    @Override
    public Page<Article> list(int page, int size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "created");
        PageRequest pageRequest = PageRequest.of(page, size, sort);
        Page<Article> pageList = articleRepository.findAll(pageRequest);
        return pageList;
    }

    @Override
    public Article findById(Article article) {
        Object o = redisTemplate.opsForValue().get("article_" + article.getId());
        if(o != null) {
            return (Article) o;
        }
        Optional<Article> repositoryById = articleRepository.findById(article.getId());
        if(repositoryById.isPresent()) {
            redisTemplate.opsForValue().set("article_" + article.getId(), repositoryById.get());
            return repositoryById.get();
        }
        return null;
    }

    @Override
    public Integer update(String content, Integer id) {
        int update = articleRepository.update(content, id);
        Optional<Article> byId = articleRepository.findById(id);
        redisTemplate.opsForValue().set("article_" + id, byId.get());
        return update;
    }
}
